package csc.traning.wpsj.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import csc.traning.wpsj.dao.User;

/**
 * Servlet implementation class ViewUsers
 */
public class ViewUsers extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String destination_dir_path = "";
	private File destinationDir;
	private static double MAX_SIZE = 1073741824D;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ViewUsers() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		try {
			User user = (User) session.getAttribute("user");
			if (user == null) {
				throw new ServletException("Required to login");
			}
			destination_dir_path = new StringBuffer("users/").append(user.getUserName()).append("/upload-folder").toString();
			destinationDir = new File(getServletContext().getRealPath(
					destination_dir_path));
			if (!destinationDir.isDirectory()) {
				destinationDir.mkdirs();
			}

			double capacity = 0;
			if (destinationDir.exists()) {
				long folderSize = folderSize(destinationDir);
				capacity = folderSize / MAX_SIZE;
			}
			request.setAttribute("capacity", capacity);
			//session.setAttribute("users", UserDB.getUserList());
		} catch (Exception e) {
			throw new ServletException(e.getMessage());
		}

		RequestDispatcher dispatcher = request
				.getRequestDispatcher("profile_editor.jsp");
		dispatcher.forward(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	public static long folderSize(File directory) {
		long length = 0;
		for (File file : directory.listFiles()) {
			if (file.isFile())
				length += file.length();
			else
				length += folderSize(file);
		}
		return length;
	}
}
